package com.wu01.demo.component;


import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

//    @Autowired
//    private IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 将请求的url对应的角色加入到SecurityConfig中
     * @param o
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        //查询出来了每一个菜单及其对应所需要的角色
//        List<Menu> menus = menuService.getMenusWithRole(requestUrl);
//        //遍历资源，查找用户访问的资源
//        for (Menu menu : menus) {
//            //判断请求url与菜单角色是否匹配
//            if(antPathMatcher.match(menu.getUrl(), requestUrl)){
//                //将url匹配到的菜单所需要的所有角色加入到Security中
//                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
//                //返回角色列表Collection<ConfigAttribute>
//                return SecurityConfig.createList(str);
//            }
//        }
        //没有匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}